<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录 - 电商平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            padding: 40px;
            width: 400px;
            max-width: 90vw;
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-header h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }

        .login-header p {
            color: #666;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }

        .form-options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .remember-me {
            display: flex;
            align-items: center;
        }

        .remember-me input {
            margin-right: 5px;
        }

        .forgot-password {
            color: #667eea;
            text-decoration: none;
        }

        .forgot-password:hover {
            text-decoration: underline;
        }

        .login-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .login-btn:hover {
            transform: translateY(-2px);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .register-link {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #666;
        }

        .register-link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }

        .register-link a:hover {
            text-decoration: underline;
        }

        .error-message {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .success-message {
            color: #27ae60;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        @media (max-width: 480px) {
            .login-container {
                padding: 30px 20px;
            }

            .form-options {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="login-header">
        <h1>用户登录</h1>
        <p>欢迎回到电商平台</p>
    </div>

    <form id="loginForm">
        <div class="form-group">
            <label for="account">用户名</label>
            <input type="text" id="account" name="account" placeholder="请输入用户名" required>
            <div class="error-message" id="accountError"></div>
        </div>

        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" placeholder="请输入密码" required>
            <div class="error-message" id="passwordError"></div>
        </div>

        <div class="form-options">
            <label class="remember-me">
                <input type="checkbox" id="rememberMe" name="rememberMe">
                <span>记住用户名</span>
            </label>
            <a href="forgot-password.html" class="forgot-password">忘记密码？</a>
        </div>

        <button type="submit" class="login-btn" id="loginBtn">登录</button>

        <div class="error-message" id="loginError"></div>
        <div class="success-message" id="loginSuccess"></div>
    </form>

    <div class="register-link">
        还没有账号？<a href="register.html">免费注册</a>
    </div>
</div>

<script>

    document.addEventListener('DOMContentLoaded', function() {
        const loginForm = document.getElementById('loginForm');
        const loginBtn = document.getElementById('loginBtn');
        const loginError = document.getElementById('loginError');
        const loginSuccess = document.getElementById('loginSuccess');

        // 页面加载时检查是否有保存的用户名
        const savedUsername = localStorage.getItem('rememberedUsername');
        if (savedUsername) {
            document.getElementById('account').value = savedUsername;
            document.getElementById('rememberMe').checked = true;
        }

        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            // 清除之前的错误信息
            clearMessages();

            const account = document.getElementById('account').value.trim();
            const password = document.getElementById('password').value.trim();
            const rememberMe = document.getElementById('rememberMe').checked;

            // 验证输入
            if (!account) {
                showError('accountError', '请输入用户名');
                return;
            }

            if (!password) {
                showError('passwordError', '请输入密码');
                return;
            }

            // 禁用登录按钮
            loginBtn.disabled = true;
            loginBtn.textContent = '登录中...';

            try {
                const response = await fetch('/api/user/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        account: account,
                        password: password,
                        rememberMe: rememberMe
                    })
                });

                // 检查响应状态码
                if (!response.ok) {
                    // 尝试读取错误信息
                    const errorText = await response.text();
                    console.error('登录失败:', errorText);
                    showError('loginError', `登录失败 (${response.status}): ${response.statusText}`);
                    return;
                }

                // 检查响应内容类型
                const contentType = response.headers.get('Content-Type');
                if (!contentType || !contentType.includes('application/json')) {
                    const errorText = await response.text();
                    console.error('服务器返回非JSON格式:', errorText);
                    showError('loginError', '服务器返回异常，请稍后再试');
                    return;
                }

                // 处理JSON响应
                const result = await response.json();

                if (result.code === 200) {
                    // 登录成功
                    showSuccess('loginSuccess', '登录成功，正在跳转...');

                    // 保存用户名（如果勾选了记住用户名）
                    if (rememberMe) {
                        localStorage.setItem('rememberedUsername', account);
                    } else {
                        localStorage.removeItem('rememberedUsername');
                    }

                    // 保存token和角色信息
                    const loginData = result.data;
                    localStorage.setItem('token', loginData.token);
                    localStorage.setItem('userRole', loginData.role);

                    // 根据角色跳转到不同页面
                    setTimeout(() => {
                        if (loginData.role === 2) {
                            // 管理员角色，跳转到管理后台
                            window.location.href = 'admin.html';
                        } else {
                            // 普通用户角色，跳转到用户首页
                            window.location.href = 'index.html';
                        }
                    }, 1000);
                } else {
                    // 登录失败
                    showError('loginError', result.message || '登录失败');
                }
            } catch (error) {
                console.error('登录请求失败:', error);
                showError('loginError', '网络错误，请重试');
            } finally {
                // 恢复登录按钮
                loginBtn.disabled = false;
                loginBtn.textContent = '登录';
            }
        });

        function clearMessages() {
            document.querySelectorAll('.error-message, .success-message').forEach(el => {
                el.style.display = 'none';
                el.textContent = '';
            });
        }

        function showError(elementId, message) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.style.display = 'block';
        }

        function showSuccess(elementId, message) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.style.display = 'block';
        }
    });
</script>
</body>
</html>